import { http } from "@/utils/http";
import axios from "axios";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

// GET请求辅助函数（使用params而不是data）
const taskRequestGet = <T>(url: string, params?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>("get", url, {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

/** 优化的资产查询接口（含漏洞信息） */
export const getOptimizedAssetQuery = (data?: {
  page?: number;
  per_page?: number;
  ip?: string;
  status?: string;
  department?: string;
  contact_person?: string;
  has_vulnerability?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/asset/optimized_query", { ...data });
};

/** IP详情查询接口 */
export const getIpDetail = (data?: { ip: string }) => {
  return taskRequest<Result>("post", "/api/asset/ip_detail", { ...data });
};

/** 导出合规资产扫描分析数据 */
export const exportComplianceAssets = async (data?: {
  task?: string;
  ip?: string;
  owner?: string;
  department?: string;
  start_time?: string;
  end_time?: string;
  severity_min?: "critical" | "high" | "medium" | "low" | "info";
  include_library?: boolean;
  mask_sensitive?: boolean;
  async?: boolean;
}) => {
  // 直接使用 axios 绕过响应拦截器，避免 Blob 被当作 JSON 处理
  const token = getToken175();

  const response = await axios.post(
    "/api/asset/export_compliance_assets",
    { ...data },
    {
      headers: {
        "Content-Type": "application/json",
        Authorization: token ? `Bearer ${token}` : undefined,
      },
      responseType: "blob",
    }
  );

  return response.data; // 返回 Blob 对象
};

// ============ 白名单管理 API ============

/** 查询加白规则列表 */
export const getWhitelistRules = (params?: {
  page?: number;
  page_size?: number;
  rule_type?: string; // ip/ip_range/port/ip_port/scene/vuln_type
  is_enabled?: boolean;
  created_by?: string;
  keyword?: string;
  start_time?: string;
  end_time?: string;
  sort_by?: string; // created_at/match_count/rule_name
  sort_order?: string; // asc/desc
}) => {
  return taskRequestGet<Result>("/api/whitelist/rules", params);
};

/** 获取规则详情 */
export const getWhitelistRuleDetail = (id: number | string) => {
  return taskRequestGet<Result>(`/api/whitelist/rules/${id}`);
};

/** 获取统计数据 */
export const getWhitelistStatistics = () => {
  return taskRequestGet<Result>("/api/whitelist/statistics");
};

/** 创建加白规则 */
export const createWhitelistRule = (data: {
  rule_name: string;
  rule_type: string; // ip/ip_range/port/ip_port/scene/vuln_type
  match_condition: string | object;
  rule_description?: string;
  applicable_dimensions?: string;
  effective_start?: string | null;
  effective_end?: string | null;
  is_enabled?: boolean;
  created_by?: string;
}) => {
  return taskRequest<Result>("post", "/api/whitelist/rules", data);
};

/** 更新加白规则 */
export const updateWhitelistRule = (
  id: number | string,
  data: {
    rule_name?: string;
    rule_description?: string;
    match_condition?: string | object;
    applicable_dimensions?: string;
    effective_start?: string | null;
    effective_end?: string | null;
    is_enabled?: boolean;
  }
) => {
  return taskRequest<Result>("put", `/api/whitelist/rules/${id}`, data);
};

/** 删除加白规则 */
export const deleteWhitelistRule = (id: number | string) => {
  return taskRequest<Result>("delete", `/api/whitelist/rules/${id}`);
};

/** 启用/禁用规则 */
export const toggleWhitelistRule = (
  id: number | string,
  is_enabled: boolean
) => {
  return taskRequest<Result>("post", `/api/whitelist/rules/${id}/toggle`, {
    is_enabled,
  });
};

/** 批量操作规则 */
export const batchWhitelistRules = (data: {
  action: "enable" | "disable" | "delete";
  rule_ids: number[];
}) => {
  return taskRequest<Result>("post", "/api/whitelist/rules/batch", data);
};

// ============ 告警审核中心 API ============

/** 获取告警列表 */
export const getAlertList = (data?: {
  page?: number;
  per_page?: number;
  scene_type?: string;
  review_status?: string;
  risk_level?: string;
  responsible_person?: string;
  department?: string;
  start_time?: string;
  end_time?: string;
  keyword?: string;
  sort_by?: string;
  sort_order?: string;
}) => {
  return taskRequest<Result>("post", "/api/alert/get_alert_list", data);
};

/** 获取告警统计数据 */
export const getAlertStatistics = (data?: {
  start_time?: string;
  end_time?: string;
}) => {
  return taskRequest<Result>("post", "/api/alert/get_statistics", {});
};

/** 获取筛选选项 */
export const getAlertFilterOptions = () => {
  return taskRequest<Result>("post", "/api/alert/get_filter_options", {});
};

/** 获取告警详情 */
export const getAlertDetail = (data: { alert_id: string }) => {
  return taskRequest<Result>("post", "/api/alert/get_detail", data);
};

/** 审核单个告警 */
export const reviewAlert = (data: {
  alert_id: string;
  review_decision: "confirmed" | "false_positive" | "ignored";
  review_comment?: string;
  add_to_whitelist?: boolean;
  whitelist_config?: {
    rule_name: string;
    rule_type: string;
    rule_description?: string;
    match_condition: string;
    applicable_dimensions?: string;
    is_enabled?: boolean;
  };
}) => {
  return taskRequest<Result>("post", "/api/alert/review", data);
};

/** 批量审核告警 */
export const batchReviewAlerts = (data: {
  alert_ids: string[];
  review_decision: "confirmed" | "false_positive" | "ignored";
  review_comment?: string;
}) => {
  return taskRequest<Result>("post", "/api/alert/batch_review", data);
};

/** 获取审核历史 */
export const getAlertReviewHistory = (data: { alert_id: string }) => {
  return taskRequest<Result>("post", "/api/alert/get_review_history", data);
};

// ============ 数据统计看板 API ============

/** 获取概览数据（组合工单和告警统计） */
export const getOverviewData = () => {
  return taskRequest<Result>("post", "/api/dashboard/overview", {});
};

/** 获取调度状态 */
export const getScheduleStatus = () => {
  return taskRequestGet<Result>("/api/scheduler/intelligence/status");
};

/** 手动触发调度任务 */
export const runScheduleTask = (type: "alert" | "intel") => {
  if (type === "intel") {
    return taskRequest<Result>(
      "post",
      "/api/scheduler/intelligence/trigger",
      {}
    );
  }
  // 告警检测调度暂不支持手动触发
  return Promise.reject(new Error("告警检测调度暂不支持手动触发"));
};

/** 获取部门排名 */
export const getDepartmentRanking = (data?: {
  dimension?: "综合评分" | "告警数量" | "响应速度" | "解决率";
  time_range?: "7d" | "30d" | "90d" | "365d";
  days?: string; // 兼容旧参数
  type?: string; // 兼容旧参数
}) => {
  // 兼容旧参数格式
  let dimension = data?.dimension;
  let time_range = data?.time_range;

  if (data?.type) {
    const typeMap: Record<string, string> = {
      score: "综合评分",
      alerts: "告警数量",
      response: "响应速度",
      solveRate: "解决率",
    };
    dimension = (typeMap[data.type] || "综合评分") as any;
  }

  if (data?.days) {
    const daysMap: Record<string, string> = {
      "7": "7d",
      "30": "30d",
      "90": "90d",
      "365": "365d",
    };
    time_range = (daysMap[data.days] || "30d") as any;
  }

  return taskRequest<Result>("post", "/api/ranking/get_department_ranking", {
    dimension: dimension || "综合评分",
    time_range: time_range || "30d",
  });
};

/** 获取排名趋势 */
export const getRankingTrend = (data: {
  department: string;
  time_range?: "7d" | "30d" | "90d";
}) => {
  return taskRequest<Result>("post", "/api/ranking/get_ranking_trend", {
    department: data.department,
    time_range: data.time_range || "30d",
  });
};

/** 获取维度详情 */
export const getDimensionDetails = (data: {
  department: string;
  dimension: string;
  time_range?: "7d" | "30d" | "90d";
}) => {
  return taskRequest<Result>("post", "/api/ranking/get_dimension_details", {
    department: data.department,
    dimension: data.dimension,
    time_range: data.time_range || "30d",
  });
};

/** 获取工单统计 */
export const getWorkorderStatistics = () => {
  return taskRequest<Result>("post", "/api/ticket/get_statistics", {});
};

/** 获取工单状态分布数据（用于图表） */
export const getWorkorderStatusData = async () => {
  try {
    const result = await getWorkorderStatistics();
    if (result?.data?.by_status) {
      const statusMap = result.data.by_status;
      return [
        { name: "已解决", value: statusMap.resolved?.count || 0 },
        { name: "处理中", value: statusMap.processing?.count || 0 },
        { name: "待审核", value: statusMap.pending_review?.count || 0 },
        { name: "已拒绝", value: statusMap.rejected?.count || 0 },
        { name: "待处理", value: statusMap.approved?.count || 0 },
      ];
    }
    return [];
  } catch (error) {
    console.error("获取工单状态数据失败:", error);
    return [];
  }
};

/** 获取告警风险等级分布数据（用于图表） */
export const getRiskLevelData = async () => {
  try {
    const result = await getAlertStatistics();
    if (result?.data?.by_risk_level) {
      const riskMap = result.data.by_risk_level;
      return [
        { name: "严重", value: riskMap.critical || 0 },
        { name: "高", value: riskMap.high || 0 },
        { name: "中", value: riskMap.medium || 0 },
        { name: "低", value: riskMap.low || 0 },
      ];
    }
    return [];
  } catch (error) {
    console.error("获取风险等级数据失败:", error);
    return [];
  }
};

/** 获取趋势数据 */
export const getTrendData = (data?: {
  range?: string | number; // "7" | "30" | "90" | "year"
}) => {
  // 将 range 转换为接口需要的格式
  let timeRange = "30d";
  if (data?.range) {
    if (typeof data.range === "number") {
      timeRange = `${data.range}d`;
    } else if (data.range === "year") {
      timeRange = "365d";
    } else {
      timeRange = `${data.range}d`;
    }
  }

  // 这里需要调用告警趋势接口，如果后端有的话
  // 暂时返回告警统计数据，前端可以基于此生成趋势
  return taskRequest<Result>("post", "/api/alert/get_statistics", {
    time_range: timeRange,
  });
};

// ============ 工单管理中心 API ============

/** 获取工单列表 */
export const getTicketList = (data?: {
  page?: number;
  per_page?: number;
  ticket_status?: string;
  ticket_type?: string;
  priority?: string;
  responsible_person?: string;
  department?: string;
  reviewer_name?: string;
  start_time?: string;
  end_time?: string;
  keyword?: string;
  sort_by?: string;
  sort_order?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/get_ticket_list", data);
};

/** 获取工单统计数据 */
export const getTicketStatistics = (data?: {
  start_time?: string;
  end_time?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/get_statistics", data);
};

/** 获取筛选选项 */
export const getTicketFilterOptions = () => {
  return taskRequest<Result>("post", "/api/ticket/get_filter_options", {});
};

/** 获取工单详情 */
export const getTicketDetail = (data: { ticket_id: string }) => {
  return taskRequest<Result>("post", "/api/ticket/get_detail", data);
};

/** 审核单个工单 */
export const reviewTicket = (data: {
  ticket_id: string;
  review_decision: "approved" | "rejected";
  review_comment?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/review_ticket", data);
};

/** 批量审核工单 */
export const batchReviewTickets = (data: {
  ticket_ids: string[];
  review_decision: "approved" | "rejected";
  review_comment?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/batch_review_tickets", data);
};

/** 推送工单到OA系统 */
export const pushTickets = (data: { ticket_id: string }) => {
  return taskRequest<Result>("post", "/api/ticket/push", data);
};

/** 导出工单Excel */
export const exportTicketExcel = async (data?: {
  ticket_status?: string;
  ticket_type?: string;
  priority?: string;
  responsible_person?: string;
  department?: string;
  reviewer_name?: string;
  start_time?: string;
  end_time?: string;
  keyword?: string;
  sort_by?: string;
  sort_order?: string;
}) => {
  const token = getToken175();
  const response = await axios.post(
    "/api/ticket/export",
    { ...data },
    {
      headers: {
        "Content-Type": "application/json",
        Authorization: token ? `Bearer ${token}` : undefined,
      },
      responseType: "blob",
    }
  );
  return response;
};

/** 关闭工单 */
export const closeTicket = (data: {
  ticket_id: string;
  close_reason: string;
  close_note?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/close_ticket", data);
};

/** 批量关闭工单 */
export const batchCloseTickets = (data: {
  ticket_ids: string[];
  close_reason: string;
  close_note?: string;
}) => {
  return taskRequest<Result>("post", "/api/ticket/batch_close_tickets", data);
};

/** 获取关联告警 */
export const getTicketAlerts = (data: { ticket_id: string }) => {
  return taskRequest<Result>("post", "/api/ticket/get_alerts", data);
};

/** 获取审核历史 */
export const getTicketReviewHistory = (data: { ticket_id: string }) => {
  return taskRequest<Result>("post", "/api/ticket/get_review_history", data);
};

/** 获取推送日志 */
export const getTicketPushLogs = (data: { ticket_id: string }) => {
  return taskRequest<Result>("post", "/api/ticket/get_push_logs", data);
};
